import shell from "shelljs";
import fs from "fs";
import path from "path";
import xml from "xml2js";
const { parseString, Builder } = xml;
let config = {};
let currentType = {};
const typeExtRun = {
  backend: (module) => {
    if (currentType.multiModule) {
      addModuleInXml("./", module.value);
      addModuleToMainXml("./", module.value);
      shell.exec(`git add .`);
      shell.exec(
        `git commit -m "feat(sys-auth): 添加${module.name}\n${module.description}"`
      );
    }
  },
};
function delDir(path) {
  // 如果目录存在，删除目录
  if (fs.existsSync(path)) {
    // 递归删除一个文件夹
    fs.rmSync(path, { recursive: true, force: true });
  }
}
function cloneModules(answers) {
  for (let index = 0; index < answers.module.length; index++) {
    const element = answers.module[index];
    cloneModule(element);
  }
}
function cloneModule(moduleFlag) {
  const module = config.modules.find((it) => (it.value = moduleFlag));
  if (module) {
    fs.access(moduleFlag, (err) => {
      if (err) {
        shell.exec(`git clone ${module.gitTemplateUrl} ${moduleFlag}`);
        delDir(`./${module.value}/.git`);
        typeExtRun[currentType.type] && typeExtRun[currentType.type](module);
      } else {
        console.error(`${module.name}已存在，无需添加`);
      }
    });
  }
}
function addModuleInXml(__dirname, newModule) {
  // 读取 pom.xml 文件
  const pomPath = path.resolve(__dirname, "pom.xml");
  readXmlResult(pomPath, (result) => {
    // 获取 <modules> 节点
    let modules = result.project.modules[0];
    // 添加新模块（确保不重复）
    if (!modules.module.includes(newModule)) {
      modules.module.push(newModule);
    }
    const builder = new Builder({ indent: "  ", newline: "\n" });
    const newXml = builder.buildObject(result);
    // 写入文件
    fs.writeFile(pomPath, newXml, (writeErr) => {
      if (writeErr) throw writeErr;
      console.log(newModule + "模块已成功添加到 pom.xml");
    });
  });
}
function addDependenciesInXml(__dirname, groupId, artifactId, version) {
  // 读取 pom.xml 文件
  const pomPath = path.resolve(__dirname, "pom.xml");
  readXmlResult(pomPath, (result) => {
    // 获取 <modules> 节点
    let dependencies = result.project.dependencies[0];
    const find = dependencies.dependency.find(
      (ite) =>
        ite.groupId[0] == groupId &&
        ite.artifactId[0] == artifactId &&
        ite.version[0] == version
    );
    if (find) {
      console.log("已填加" + groupId + "依赖，无需再操作");
    } else {
      dependencies.dependency.push({
        groupId: [groupId],
        artifactId: [artifactId],
        version: [version],
        scope: ["compile"],
      });
    }
    const builder = new Builder({ indent: "  ", newline: "\n" });
    const newXml = builder.buildObject(result);
    // 写入文件
    fs.writeFile(pomPath, newXml, (writeErr) => {
      if (writeErr) throw writeErr;
      console.log(`为项目添加${artifactId}模块maven依赖`);
      shell.exec(`git add .`);
      shell.exec(`git commit -m "feat: 为项目添加${artifactId}模块依赖"`);
    });
  });
}

function readXmlResult(path, callback) {
  fs.readFile(path, "utf8", (err, data) => {
    if (err) {
      console.error("读取 pom.xml 失败:", err);
      return;
    }

    // 解析 XML
    parseString(data, (parseErr, result) => {
      if (parseErr) {
        console.error("解析 XML 失败:", parseErr);
        return;
      }
      callback && callback(result);
    });
  });
}
function addModuleToMainXml(__dirname, newModule) {
  // 读取 pom.xml 文件
  const pomPath = path.resolve(__dirname + newModule, "pom.xml");
  readXmlResult(pomPath, (result) => {
    addDependenciesInXml(
      __dirname + (currentType.mainModule || "main-entrance"),
      result.project.groupId[0],
      result.project.artifactId[0],
      result.project.version[0]
    );
  });
}

export function initProject(answers, _config) {
  config = _config;
  const template = config.types.find((it) => it.value === answers.type);
  if (template) {
    currentType = template;
    shell.exec(`git clone ${template.gitTemplateUrl} ${answers.projectName}`);
    //清理git目录
    delDir(`./${answers.projectName}/.git`);
    shell.cd(`${answers.projectName}`);
    shell.exec(`git init`);
    shell.exec(`git add .`);
    shell.exec(`git commit -m "feat: 项目初始化"`);
    addModule(answers, config);
  }
}
export function addModule(answers, _config) {
  config = _config;

  cloneModules(answers);
}

export default initProject;
